// myapp下的api是   服务端和数据库端的通信

const mongoose = require('mongoose');

const get = async ({ curPage, eachPage }) => {
    // 解构，类型转换
    (curPage = ~~curPage), (eachPage = ~~eachPage);
    const data = {
        total: 0,
    };
    // 拿到cinemas影院对象模型
    const cinemasModel = mongoose.model('cinemas');
    // 获取数据库中cinemas集合中的文档总数
    data.total = await cinemasModel.countDocuments();
    // 获取最大页（总页数除以一页显示数）
    data.maxPage = Math.ceil(data.total / eachPage);
    // 跳过总数（上一页页数*一页展示总数）
    const skipNum = (curPage - 1) * eachPage;
    data.rows = await cinemasModel.find().populate().skip(skipNum).limit(eachPage).sort({ _id: -1 }).exec();
    return data;
}

// 删除影院
const removeCinemas = async ({ _id }) => {
    const cinemasModel = mongoose.model("cinemas");
    // remove删除数据库_id匹配的数据
    await cinemasModel.remove({ _id });
}
// 新增影院
const add = async ({ name, address, phone, price, distance, status, }) => {
    const cinemasModel = mongoose.model("cinemas");
    const searchName = await cinemasModel.findOne({ name })
    // 查找数据库中是否存在这个名字，
    if (searchName) {
        return false
    } else {
        return await cinemasModel.create({
            name, address, phone, price, distance, status,
        })
    }
};
// 修改影院
const updateCinema = async (newData, _id) => {
    const cinemasModel = mongoose.model("cinemas");
    await cinemasModel.updateOne({ _id: newData._id }, newData);
}
// 通过_id值获取整条信息
const getOne = async _id => {
    const cinemasModel = mongoose.model('cinemas');
    return await cinemasModel.findOne({ _id });
};
// query    查询条件    parmas  需要修改的数据
const update = async (query, params) => {
    const cinemasModel = mongoose.model('cinemas');
    await cinemasModel.updateOne(query, params);
    return cinemasModel.findOne(query);
}
const delImgs = async ({ _id, url }) => {
    const cinemasModel = mongoose.model('cinemas');
    const cinema = await cinemasModel.findOne({ _id });
    cinema.imgs.pull(url);
    await cinema.save();
}
// 查找匹配的信息
const select = async (data) => {
    const cinemasModel = mongoose.model("cinemas");
    return await cinemasModel.find(data);
}



// 暴露方法
module.exports = { get, removeCinemas, add, updateCinema, getOne, update, delImgs,select};